package com.atguigu.srb.core.controller;


import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author LiLi
 * @since 2021-09-23
 */
@RestController
@RequestMapping("/api/core/userAccount")
@Api
public class UserAccountController {
    @Autowired
    UserAccountService userAccountService;
    @Autowired
    TransFlowService transFlowService;
    @ApiOperation("充值")
    @PostMapping("/auth/commitCharge/{chargeAmt}")
    public R commitCharge(
            @ApiParam("充值金额")
            @PathVariable BigDecimal chargeAmt, HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        String formStr = userAccountService.commitCharge(chargeAmt,userId);
        return R.ok().data("formStr",formStr);
    }
    @ApiOperation("充值")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> stringObjectMap = RequestHelper.switchMap(parameterMap);

        String agentBillNo = (String) stringObjectMap.get("agentBillNo");
        //幂等性校验
        boolean b = transFlowService.isSaveTransFlow(agentBillNo);
        Assert.isTrue(b, ResponseEnum.RESPONSE_CHONGFU);
        if(RequestHelper.isSignEquals(stringObjectMap)){//先判断回调签名是否正确
            if("0001".equals((String)stringObjectMap.get("resultCode"))){//再判断回调码
                userAccountService.hfbNotify(stringObjectMap);
            }
        }
        return "success";
    }

    @ApiOperation("查询账户余额")
    @GetMapping("/auth/getAccount")
    public R getAccount(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        BigDecimal account = userAccountService.getAccount(userId);
        return R.ok().data("account",account);
    }
}

